package 文件IO.歌曲转移;

import java.io.*;

public class Main {
    public static void main(String[] args) {
        String oldPath = "F:/Music/Old";//音乐根目录
        String targetPath = "F:/Music/Target";//目标目录
        String keyWord1 = "mp3";
        String keyWord2 = "flac";
        //限制目标目录是否合法
        File oldFile = new File(oldPath);
        if(!oldFile.isDirectory()){
            System.out.println("音乐目标目录不合法");
            return;
        }
        //歌曲转移
        SearchFile(oldFile, targetPath, keyWord1, keyWord2);
    }

    private static void SearchFile(File oldFile, String targetPath, String keyWord1, String keyWord2) {
        File targetDir = new File(targetPath);
        if (!targetDir.isDirectory()) {
            System.out.println("目标路径不合法");
            return;
        }

        File[] files = oldFile.listFiles(file -> file.isFile());
        if (files == null) {
            System.out.println("目录读取失败或目录为空");
            return;
        }

        for (File file : files) {
            String fileName = file.getName();
            if (fileName.contains(keyWord1) || fileName.contains(keyWord2)) {
                File targetFile = new File(targetDir, fileName);
                try (InputStream inputStream = new FileInputStream(file);
                     OutputStream outputStream = new FileOutputStream(targetFile)) {

                    byte[] buffer = new byte[4096];
                    int bytesRead;
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, bytesRead);
                    }

                    System.out.println("复制 :" + fileName + " 到 " + targetFile.getPath() + " 完成");
                    // 删除源文件
                    if (file.delete()) {
                        System.out.println("删除源文件 :" + fileName + " 成功");
                    } else {
                        System.out.println("删除源文件 :" + fileName + " 失败");
                    }
                } catch (IOException e) {
                    System.err.println("复制失败: " + fileName);
                    e.printStackTrace();
                }
            }
        }
    }
}
